package jk.spider.core.event.URLFound.impl;

import java.util.Set;

import jk.spider.core.SpiderController;
import jk.spider.core.event.CoreEvent;
import jk.spider.core.event.URLFound.URLFound;
import jk.spider.core.event.impl.URLFoundEvent;
import jk.spider.core.task.work.SpiderHttpURLTask;
import jk.spider.model.Resource;

import org.apache.log4j.Logger;

public class ReviewURLFound extends URLFound {
	private static final Logger log = Logger.getLogger(ReviewURLFound.class);
	
	public static final String URL_PLUGIN_NAME = "REVIEW URL FOUND";
    public static final String URL_PLUGIN_VERSION = "v1.0";
    public static final String URL_PLUGIN_DESCRIPTION = "";
    
    public ReviewURLFound(String reg) {
		super(reg);
	}
    
    public ReviewURLFound(String reg, Set<String> filterSet) {
		super(reg, filterSet);
	}
    
	public boolean findUrl(URLFoundEvent event) {
		SpiderController controller = event.getController();
		Resource eventRes = event.getResource(); 
		String dUrl = event.getSrc();
		
		if(dUrl.endsWith("%7D}") || dUrl.endsWith("%7D") || dUrl.endsWith("}"))
			return false;
		
		if(!this.isUrlValid(dUrl))
			return false;
		
		Resource deRes = new Resource();
		deRes.setUrl(dUrl);
		int paId = -1;
		if(eventRes.getType().equals(CoreEvent.COREEVENT_DETAIL) || eventRes.getType().equals(CoreEvent.COREEVENT_MONITOR))
			paId = eventRes.getRId();
		else if (eventRes.getType().equals(CoreEvent.COREEVENT_REVIEW))
			paId = eventRes.getPaId();
		if(paId == -1)
			return false;
		deRes.setPaId(paId);
		deRes.setType(CoreEvent.COREEVENT_REVIEW);
		if(controller.getStorage().getResourceDAO().create(deRes)) {
			log.info("[FOUND] @ [REVIEW] @ [" + dUrl + "] PAID [" + deRes.getPaId() + "]");
			controller.getContent().schedule(new SpiderHttpURLTask(controller, controller.getStorage().getResourceDAO().getResource(deRes.getUrl())));
		} 
		return true;
	}
	
	public void initialize() {
		log.info(URL_PLUGIN_NAME);
		log.info(URL_PLUGIN_VERSION);
		log.info(URL_PLUGIN_DESCRIPTION);
	}
	
	@Override
	public String getUrlFoundType() {
		return CoreEvent.COREEVENT_REVIEW;
	}

}
